package com.ffs.persist.utils;

import java.io.*;

/**
 * 文件工具
 *
 * @author ffs80
 */
@SuppressWarnings("all")
public class FileUtil {

    /**
     * 输出文件
     *
     * @param clazz    对象
     * @param filePath 文件路径（不包含文件名）
     */
    public static <T> void outFile(Class<T> clazz, T object, String filePath) {
        File file = new File(filePath);
        //目录不存在，创建目录
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
            if (!mkdirs) {
                return;
            }
        }

        //使用类名做文件名字
        String[] split = clazz.getName().split("\\.");
        String name = split[split.length - 1];
        String fileName = filePath + "/" + name + ".world";

        byte[] bytes = SerializerUtil.encode(object, clazz);

        try {
            FileOutputStream outputStream = new FileOutputStream(fileName);
            BufferedOutputStream bufferOut = new BufferedOutputStream(outputStream);
            bufferOut.write(bytes);
            bufferOut.flush();
            bufferOut.close();
            outputStream.close();
        } catch (Exception e) {

        }
    }

    /**
     * 从文件中获取对象
     *
     * @param clazz    类对象
     * @param filePath 文件路径（不包含文件名）
     */
    public static <T> T inputObject(Class<T> clazz, String filePath) {
        File file = new File(filePath);
        //文件目录不存在
        if (!file.exists()) {
            return null;
        }

        String[] split = clazz.getName().split("\\.");
        String name = split[split.length - 1];
        String fileName = filePath + "/" + name + ".world";

        File inFile = new File(fileName);
        T object = null;

        try {
            FileInputStream inputStream = new FileInputStream(fileName);
            BufferedInputStream bufferInput = new BufferedInputStream(inputStream);
            byte[] bytes = new byte[(int) inFile.length()];
            bufferInput.read(bytes);
            object = SerializerUtil.decode(bytes, clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

}
